package com.piesat.quake.business.device.mqtt.convert;

import com.piesat.quake.business.device.mqtt.param.ParseParam;

import io.netty.buffer.ByteBuf;

/**
 * ip转换器
 *
 * @author Gersy
 * @date 2023/3/10
 * @since 1.0
 */
public class IpConvert implements Convert {
    @Override
    public String read(ByteBuf byteBuf, ParseParam param) {
        byte[] bytes = new byte[4];
        byteBuf.readBytes(bytes);
        int number = 0xFF & bytes[0];
        StringBuilder sb = new StringBuilder();
        sb.append(number);
        for (int i = 1; i < bytes.length; i++) {
            sb.append('.').append(0xFF & bytes[i]);
        }
        return sb.toString();
    }

    @Override
    public void write(ByteBuf byteBuf, Object obj, ParseParam param) {
        String ip = (String) obj;
        String[] numbers = ip.split("\\.");
        for (String number : numbers) {
            short b = Short.parseShort(number);
            byteBuf.writeByte((byte) (b & 0xFF));
        }
    }
}
